package com.qf.ems.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {


    private static SqlSessionFactory factory;

    //每个线程有自己的conneciton
    //每个线程要有自己的sqlsession
    private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // commit
    public static void commit(){
        SqlSession sqlSession = openSqlSession();
        sqlSession.commit();
        closeSession();
    }

    // 关闭数据库会话
    private static void closeSession() {
        SqlSession sqlSession = openSqlSession();
        sqlSession.close();
        threadLocal.remove(); // 需要清除掉
    }

    // rollback
    public static void rollback(){
        SqlSession sqlSession = openSqlSession();
        sqlSession.rollback();
        closeSession();
    }

    // new UserDaoImpl();
    // 获取Dao的对象
    public static <T> T getMapper(Class<T> clazz){
        SqlSession sqlSession = openSqlSession();
        return sqlSession.getMapper(clazz);
    }

    // 获得sqlsession对象
    private static SqlSession openSqlSession() {
        //每个线程有自己的SqlSession
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession==null){
            //如果没有则创建
            sqlSession=factory.openSession();
            //放入threadlocal中
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }


}
